package it.pecuswap.thread;

import org.apache.log4j.Logger;

import it.pecuswap.client.rest.service.BackendMonitorServiceClient;
import it.pecuswap.commons.exceptions.PecuswapRestException;
import it.pecuswap.commons.utils.ConfigurationKeys;
import it.pecuswap.configuration.Configuration;
import it.pecuswap.exceptions.ConfigurationException;

public class BackendMonitorThread implements Runnable{
	
	private static final Logger LOGGER = Logger.getLogger(BackendMonitorThread.class);
	private boolean isBackendAvailable = false;
	private static BackendMonitorThread instance;
	private int pollingTime = 0;
	
	private BackendMonitorThread(){
	}

	@Override
	public void run() {
		
		try {
			pollingTime = Integer.valueOf(Configuration.getInstance().getValueOf(ConfigurationKeys.BACKEND_MONITORING_SERVICE_POLLING_INTERVAL));
		} catch (NumberFormatException | ConfigurationException e1) {
			LOGGER.error("Errore di configurazione. Thread stoppato.");
		}
		
		BackendMonitorServiceClient bmsc = null;
		try {
			bmsc = new BackendMonitorServiceClient();
		} catch (ConfigurationException e1) {
			LOGGER.error("Errore di configurazione. Thread stoppato.");
		}
		while (true) {
			try {
				isBackendAvailable = bmsc.pingBackend();
				LOGGER.debug("Backend disponibile: " + isBackendAvailable);
				Thread.sleep(pollingTime);
			} catch (InterruptedException | PecuswapRestException e) {
				LOGGER.error("Errore generico. Thread stoppato.");
			}
		}
	}
	
	public static BackendMonitorThread getInstance(){
		if (instance == null){
			instance = new BackendMonitorThread();
		}
		return instance;
	}

	public boolean isBackendAvailable() {
		return isBackendAvailable;
	}

}
